<?php include("php/dao/DatabaseDAO.php");
include("php/dao/UserFeedDAO.php");

$databaseDAO = new DatabaseDAO();
$userFeedDAO = new UserFeedDAO();
$databaseNames = $databaseDAO->getUserDatabases($_SESSION["UserId"]);
$listOfFeeds = $userFeedDAO->getUserFeeds($_SESSION["UserId"]);
$listOfActionsSelect = $userFeedDAO->getActions($_SESSION["UserId"]);
$listOfActions = Array();

while ($row = mysqli_fetch_assoc($listOfActionsSelect)) {
//    $listOfActions[] = "<option value=" . $row['Id'] . ">" . $row['Description'] . "</option>";
    $listOfActions[] = $row;
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>Manage feeds</title>

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <link rel="stylesheet" href="css/style.css"/>
    <link rel="stylesheet" href="css/jquery.snippet.css"/>
    <script type="text/javascript" src="js/sh_xml.js"></script>

    <script type="text/javascript" src="js/jquery.snippet.js"></script>
</head>
<body>
<h1><a href="manage.php">Manage feeds</a> | <a href="add_new_database.php">Manage Databases</a></h1>

<h2>List of XML feeds:</h2>


<script>

var count = 1;
var secondaryTableCount = 0;
var secondaryColumnId = 0;
var secondaryTableColumnsCount = new Array();

$(document).ready(function () {

    $("#addNewFeed").click(function () {
        $("#addFeedFormContainer").show();
    });

    $("#feedDatabase").change(function (e) {
        if (!$(this).val()) {
            return;
        }
        var databaseId = "DatabaseId=" + $(this).val();
        $.ajax({
            dataType: "json",
            url: "php/GetDatabaseTables.php",
            data: databaseId,
            success: function (wrapperitems) {
                $("#feedTable").empty();
                $("#secondaryTable").empty();
                $("#secondaryTable").append($("<option value=''></option>"));
                for (var i = 0; i < items.length; i++) {
                    var item =wrapper items[i];
                    $("#feedTable").append($("<option value='" + item + "'>" + item + "</option>"));
                    $("#secondaryTable").append($("<option value='" + item + "'>" + item + "</option>"));
                }
//                    for (var obj of result) {
//                        $("#feedTable").append($("<option value='" + obj + "'>" + obj + "</option>"));
//                    }
            },
            error: function (error) {
                $("#error").html(error.responseText);
            }
        });
    });

    $("#loadXMLButton").click(function () {

    });

    $("#addFeedForm").submit(function (event) {
        event.preventDefault();

        var url = $("#feedUrl").val();
        var rootItem = $("#xmlRootItem").val();
        $.ajax({
            dataType: "xml",
            url: "php/LoadXMLFile.php",
            data: {fileUrl: url, xmlRootItem: rootItem},
            type: "POST",
            success: function (xml) {
                $("#xmlDatabaseMapping").show();
                $("#xmlPreview").text((new XMLSerializer()).serializeToString(xml));
                $("pre.xmlCode").snippet("xml");

                var firstItem = true;
                $(xml).find("*").each(function () {
                    var tagName = firstItem ? "" : this.tagName;
                    firstItem = false;
                    var parent = this.parentElement;
                    while (parent != null && parent.tagName != rootItem) {
                        tagName = parent.tagName + "->" + tagName;
                        parent = parent.parentElement;
                    }
                    if (this.children.length == 0) {
                        $("#xmlFields").append($("<option value='" + tagName + "'>" + tagName + "</option>"));
                        $("#secondaryXmlFields").append($("<option value='" + tagName + "'>" + tagName + "</option>"));
                    }
                    for (var i = 0; i < this.attributes.length; i++) {
                        var item = this.attributes[i];
                        var value = tagName + "->" + item.name;
                        if (tagName == "") {
                            value = item.name;
                        }
                        $("#xmlFields").append($("<option value='" + value + "(attribute)'>" + value + "(attribute)</option>"));
                        $("#secondaryXmlFields").append($("<option value='" + value + "(attribute)'>" + value + "(attribute)</option>"));
                    }
                });
            },
            error: function (error) {
                $("#error").html(error.responseText);
            }
        });

        var databaseId = $("#feedDatabase").val();
        var table = $("#feedTable").val();
        $.ajax({
            dataType: "json",
            url: "php/GetTableColumns.php",
            data: {databaseId: databaseId, table: table},
            type: "POST",
            success: function (items) {
                $("#tableColumns").empty();
                $("#keyColumn").empty();
                $("#dependsOn").empty();
                $("#dependsOn").append($("<option value=''></option>"));
                for (var i = 0; i < items.length; i++) {
                    var item = items[i];
                    $("#tableColumns").append($("<option value='" + item + "'>" + item + "</option>"));
                    $("#dependsOn").append($("<option value='" + item + "'>" + item + "</option>"));
                    $("#keyColumn").append($("<option value='" + item + "'>" + item + "</option>"));
                }
            },
            error: function (error) {
                $("#error").html(error.responseText);
            }
        });
    });

    $("#secondaryTable").change(function (e) {
            if (!$(this).val()) {
                return;
            }

            var databaseId = $("#feedDatabase").val();
            var table = $("#secondaryTable").val();
            $.ajax({
                dataType: "json",
                url: "php/GetTableColumns.php",
                data: {databaseId: databaseId, table: table},
                type: "POST",
                success: function (items) {
                    $("#secondaryTableColumns").empty();
                    $("#secondaryDependsOn").empty();
                    $("#secondaryDependsOn").append($("<option value=''></option>"));
                    for (var i = 0; i < items.length; i++) {
                        var item = items[i];
                        $("#secondaryTableColumns").append($("<option value='" + item + "'>" + item + "</option>"));
                        $("#secondaryDependsOn").append($("<option value='" + item + "'>" + item + "</option>"));
                    }
                },
                error: function (error) {
                    $("#error").html(error.responseText);
                }
            });
        }
    );

    $("#addNewColumnMapping").click(function () {
        var wrapper = $("#mappingFieldsWrapper").clone();
        wrapper.attr("id", "mappingFieldsWrapper" + count);
        wrapper.find(".tableColumns").attr("name", "tableColumns_" + count);
        wrapper.find(".xmlFields").attr("name", "xmlFields_" + count);
        wrapper.find(".actions").attr("name", "actions_" + count);
        wrapper.find(".defaultValue").attr("name", "defaultValue_" + count);
        wrapper.find(".plainValue").attr("name", "plainValue_" + count);
        wrapper.find(".dependsOn").attr("name", "dependsOn_" + count);
        wrapper.find(".xmlTagIndex").attr("name", "xmlTagIndex_" + count);

        count++;
        $("#mappingWrapper").append(wrapper);
        wrapper.find(".tableColumns").focus();
    });

    $("#addSecondaryTableMapping").click(function () {
        if (secondaryTableCount == 0) {
            $("#secondaryTableMappingWrapper").show();
            var mainWrapper = $("#secondaryMappingWrapper").clone();
            mainWrapper.attr("id", "secondaryMappingWrapper" + secondaryTableCount);
            mainWrapper.find("#secondaryMappingFieldsWrapper").attr("id", "secondaryMappingFieldsWrapper" + secondaryColumnId);
            mainWrapper.css("display", "auto");
            $("#secondaryTableMappingWrapper").append(mainWrapper);
            secondaryTableColumnsCount[secondaryTableCount] = [secondaryColumnId];
            secondaryTableCount++;
            return;
        }
        var wrapper = $("#secondaryMappingWrapper").clone();
        wrapper.find("#secondaryMappingFieldsWrapper").attr("id", "secondaryMappingFieldsWrapper" + secondaryColumnId);
        wrapper.css("display", "auto");
        wrapper.attr("id", "secondaryMappingWrapper" + secondaryTableCount);
        wrapper.find(".secondaryTable").attr("name", "secondaryTable_" + secondaryTableCount);
        wrapper.find(".secondaryTableColumns").attr("name", "secondaryTableColumns_" + secondaryTableCount);
        wrapper.find(".secondaryXmlFields").attr("name", "secondaryXmlFields_" + secondaryTableCount);
        wrapper.find(".secondaryActions").attr("name", "secondaryActions_" + secondaryTableCount);
        wrapper.find(".secondaryDefaultValue").attr("name", "secondaryDefaultValue_" + secondaryTableCount);
        wrapper.find(".secondaryPlainValue").attr("name", "secondaryPlainValue_" + secondaryTableCount);
        wrapper.find(".secondaryDependsOn").attr("name", "secondaryDependsOn_" + secondaryTableCount);
        wrapper.find(".secondaryXmlTagIndex").attr("name", "secondaryXmlTagIndex_" + secondaryTableCount);
        secondaryColumnId++;
        secondaryTableColumnsCount[secondaryTableCount] = [secondaryColumnId];
        secondaryTableCount++;
        $("#secondaryTableMappingWrapper").append(wrapper);
    });

    $("#addSecondaryColumnMapping").click(function () {
        var clickedItem = $(this);
        var secondaryTableId = this.parentNode.id.substring(this.parentNode.id.length - 1);
        secondaryColumnId++;
        var wrapper = $("#secondaryMappingFieldsWrapper").clone();
        wrapper.attr("id", "secondaryMappingFieldsWrapper" + secondaryColumnId);
        wrapper.find(".secondaryTableColumns").attr("name", "secondaryTableColumns_" + secondaryColumnId);
        wrapper.find(".secondaryXmlFields").attr("name", "secondaryXmlFields_" + secondaryColumnId);
        wrapper.find(".secondaryActions").attr("name", "secondaryActions_" + secondaryColumnId);
        wrapper.find(".secondaryDefaultValue").attr("name", "secondaryDefaultValue_" + secondaryColumnId);
        wrapper.find(".secondaryPlainValue").attr("name", "secondaryPlainValue_" + secondaryColumnId);
        wrapper.find(".secondaryDependsOn").attr("name", "secondaryDependsOn_" + secondaryColumnId);
        wrapper.find(".secondaryXmlTagIndex").attr("name", "secondaryXmlTagIndex_" + secondaryColumnId);
        secondaryTableColumnsCount[secondaryTableId].push(secondaryColumnId);
        var columnId = "#secondaryMappingFieldsWrapper" + (secondaryColumnId - 1);
        $(columnId).after(wrapper);
    });

    $("#saveFeedForm").submit(function (event) {
        event.preventDefault();

        // get all the inputs into an array.
        var $inputs = $('#mappingWrapper :input');

        // get all the inputs into an array.
        var $secondaryInputs = $('#secondaryTableMappingWrapper :input');

        // not sure if you wanted this, but I thought I'd add it.
        // get an associative array of just the values.
        var values = [];
        $inputs.each(function () {
            values.push($(this).val());
        });

        var numberOfFields = 7;

        var columns = [];
        for (var i = 1; i < values.length; i += numberOfFields) {
            columns.push(values[i]);
        }

        var keyColumn = values[0];
        if ($.inArray(keyColumn, columns)) {
            alert("Key column should be one of mapped columns!");
            return;
        }

        var xmlFields = [];
        for (var j = 2; j < values.length; j += numberOfFields) {
            xmlFields.push(values[j]);
        }

        var actions = [];
        for (i = 3; i < values.length; i += numberOfFields) {
            actions.push(values[i]);
        }

        var defaultValues = [];
        for (i = 4; i < values.length; i += numberOfFields) {
            defaultValues.push(values[i]);
        }

        var plainValues = [];
        for (i = 5; i < values.length; i += numberOfFields) {
            plainValues.push(values[i]);
        }

        var dependsOn = [];
        for (i = 6; i < values.length; i += numberOfFields) {
            dependsOn.push(values[i]);
        }

        var xmlTagIndex = [];
        for (i = 7; i < values.length; i += numberOfFields) {
            xmlTagIndex.push(values[i]);
        }

        var keyColumn = $("#keyColumn").val();
        var xmlRootItem = $("#xmlRootItem").val();
        var data = [];
        for (var l = 0; l < columns.length; l++) {
            var array = new Object();
            var mapping = new Object();
            var type = "tag";
            var value = xmlFields[l];
            if (plainValues[l] != "") {
                type = "value";
                value = plainValues[l];
            }
            if (xmlTagIndex[l] != "") {
                mapping['index'] = xmlTagIndex[l];
            }
            var attributeIndex = value.indexOf("(attribute)");
            if (attributeIndex != -1) {
                type = "attribute";
                value = value.substr(0, attributeIndex);
            }
            mapping['type'] = type;
            mapping['value'] = value;
            mapping['action'] = actions[l];
            mapping['default'] = defaultValues[l];
            mapping['dependsOn'] = dependsOn[l];
            if (mapping['value'] == keyColumn) {
                mapping['key'] = 1;
            } else {
                mapping['key'] = 0;
            }

            array[columns[l]] = mapping;
            data.push(array);
        }

        var url = $("#feedUrl").val();
        var feedName = $("#feedName").val();
        var xmlRootItem = $("#xmlRootItem").val();
        var databaseId = $("#feedDatabase").val();
        var table = $("#feedTable").val();
//            $.post( "php/CreateXMLFeed.php", {data: data,
//            xmlFileURL: url, xmlRootItem: xmlRootItem,
//                databaseId: databaseId} );
        $.ajax({
            dataType: "html",
            url: "php/CreateXMLFeed.php",
            data: {data: data,
                xmlRootItem: xmlRootItem,
                databaseId: databaseId,
                feedUrl: url,
                feedName: feedName,
                feedTable: table},
            type: "POST",
            success: function (text) {
                location.reload();
            },
            error: function (error) {
                $("#error").html(error.responseText);
            }
        });

//            sendRequest("php/CreateXMLFeed.php", "post", {data: data,
//                xmlRootItem: xmlRootItem,
//                databaseId: databaseId,
//                feedUrl: url,
//                feedName: feedName,
//                feedTable: table});
    });
});

function addSecondaryColumnMappingClick(item) {
    var secondaryTableId = item.parentNode.id.substring(item.parentNode.id.length - 1);
    secondaryColumnId++;
    var wrapper = $("#secondaryMappingFieldsWrapper").clone();
    wrapper.attr("id", "secondaryMappingFieldsWrapper" + secondaryColumnId);
    wrapper.find(".secondaryTableColumns").attr("name", "secondaryTableColumns_" + secondaryColumnId);
    wrapper.find(".secondaryXmlFields").attr("name", "secondaryXmlFields_" + secondaryColumnId);
    wrapper.find(".secondaryActions").attr("name", "secondaryActions_" + secondaryColumnId);
    wrapper.find(".secondaryDefaultValue").attr("name", "secondaryDefaultValue_" + secondaryColumnId);
    wrapper.find(".secondaryPlainValue").attr("name", "secondaryPlainValue_" + secondaryColumnId);
    wrapper.find(".secondaryDependsOn").attr("name", "secondaryDependsOn_" + secondaryColumnId);
    wrapper.find(".secondaryXmlTagIndex").attr("name", "secondaryXmlTagIndex_" + secondaryColumnId);
    secondaryTableColumnsCount[secondaryTableId].push(secondaryColumnId);
    var columnId = "#secondaryMappingFieldsWrapper" + (secondaryColumnId - 1).toString();
    $(columnId).after(wrapper);
}

function sendRequest(action, method, input) {
    "use strict";
    var form;
    form = $('<form />', {
        action: action,
        method: method,
        style: 'display: none;'
    });
    if (typeof input !== 'undefined') {
        $.each(input, function (name, value) {
            $('<input />', {
                type: 'hidden',
                name: name,
                value: value
            }).appendTo(form);
        });
    }
    form.appendTo('body').submit();
}

function removeBlock(item, id) {
    if (item.parentNode.id == id) {
        alert("You can't delete first item!");
        return;
    }
    item.parentNode.parentNode.removeChild(item.parentNode);
}

function removeXmlFieldMapping(item) {
    removeBlock(item, "mappingFieldsWrapper");
}

function secondaryRemoveXmlFieldMapping(item, id) {
    removeBlock(item, "secondaryMappingFieldsWrapper");
}

function secondaryTableMappingRemove(item) {
    removeBlock(item, "secondaryMappingWrapper");
}

function secondaryTableChange(select) {
    if (!$(select).val()) {
        return;
    }

    alert(select.id);

    var databaseId = $("#feedDatabase").val();
    var table = select.value;
    $.ajax({
        dataType: "json",
        url: "php/GetTableColumns.php",
        data: {databaseId: databaseId, table: table},
        type: "POST",
        success: function (items) {
            var id = "secondaryMappingWrapper" + secondaryTableCount;
            $("#secondaryTableColumns").empty();
            $("#secondaryDependsOn").empty();
            $("#secondaryDependsOn").append($("<option value=''></option>"));
            for (var i = 0; i < items.length; i++) {
                var item = items[i];
                $("#secondaryTableColumns").append($("<option value='" + item + "'>" + item + "</option>"));
                $("#secondaryDependsOn").append($("<option value='" + item + "'>" + item + "</option>"));
            }
        },
        error: function (error) {
            $("#error").html(error.responseText);
        }
    });
}
</script>
<div id="listOfXmlFeeds">
    <?php
    echo "<table class='names'>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>URL</th>
        <th>Database name</th>
        <th>Repeat time</th>
        <th>Edit</th>
        <th>Delete</th>
        <th>Run</th>
    </tr>";
    while ($row = mysqli_fetch_assoc($listOfFeeds)) {
        echo "<tr>";
        echo "<td>" . $row['Id'] . "</td>";
        echo "<td>" . $row['Name'] . "</td>";
        echo "<td>" . $row['URL'] . "</td>";
        echo "<td>" . $row['DatabaseName'] . "</td>";
        echo "<td>" . $row['RepeatTime'] . "</td>";
        echo "<td><a href='php/EditFeed.php?xmlFeedId=" . $row['Id'] . "'>edit</a> </td>";
        echo "<td><a href='php/DeleteFeed.php?xmlFeedId=" . $row['Id'] . "'>delete</a> </td>";
        echo "<td><a href='php/RunFeed.php?xmlFeedId=" . $row['Id'] . "'>run</a> </td>";
        echo "</tr>";
    }
    echo "</table>"
    ?>

    <input id="addNewFeed" type="button" class="button" value="Add new..."/>
</div>

<div id="addFeedFormContainer" style="">
    <form id="addFeedForm" action="create_feed.php" method="post">
        <label>Name:</label>
        <input type="text" name="feedName" id="feedName" placeholder="Input feed name" value="Test" required/></br>

        <label>URL:</label>
        <input type="url" name="feedUrl" id="feedUrl" placeholder="Input feed URL"
               value="http://localhost/xmltomysq/small_file.xml" required/></br>

        <label>Root item:</label>
        <input type="text" name="xmlRootItem" id="xmlRootItem" placeholder="Input root item" value="product"
               required/></br>

        <label>Database:</label>
        <select id="feedDatabase" name="feedDatabase" required>
            <option value=""></option>
            <?php
            while ($row = mysqli_fetch_assoc($databaseNames)) {
                echo "<option value=" . $row['Id'] . ">" . $row['DatabaseName'] . "</option>";
            }
            ?>
        </select>
        <a id="addNewDatabase" href="add_new_database.php">add new...</a>
        </br>

        <label>Table:</label>
        <select id="feedTable" required>

        </select></br>

        <input id="loadXMLButton" type="submit" class="button" value="Load XML">
    </form>
</div>
<div id="xmlDatabaseMapping" style="width: 100%; display: none;">
    <h2>Map columns to XML fields</h2>

    <div id="fieldsMappingContainer" style="width: 600px;">
        <form id="saveFeedForm" action="#" method="POST">
            <div id="mappingWrapper">
                <label>Key column:</label>
                <select id="keyColumn" class="keyColumn" name="keyColumn" required>
                </select></br>
                <hr class="style-one"/>
                <div id="mappingFieldsWrapper">
                    <label>Database column:</label>
                    <select id="tableColumns" class="tableColumns" name="tableColumn_0">

                    </select></br>
                    <label>Xml item:</label>
                    <select id="xmlFields" class="xmlFields" name="xmlField_0">

                    </select></br>
                    <label>Custom action:</label>
                    <select id="actions" class="actions" name="action_0">
                        <option value=""></option>
                        <?php
                        foreach ($listOfActions as $action) {
                            echo "<option value=" . $action['Id'] . ">" . $action['Description'] . "</option>";
                        }
                        ?>
                    </select></br>
                    <label>Default value:</label>
                    <input id="defaultValue" class="defaultValue" type="text" name="defaultValue_0"
                           placeholder="Input default value"/></br>
                    <label>Plain value:</label>
                    <input id="plainValue" class="plainValue" type="text" name="plainValue_0"
                           placeholder="Input plain value if needed"/></br>
                    <label>Depends on:</label>
                    <select id="dependsOn" class="dependsOn" name="dependsOn_0">

                    </select></br>
                    <label>XML tag index:</label>
                    <input id="xmlTagIndex" class="xmlTagIndex" type="number" name="xmlTagIndex_0"
                           placeholder="Input XML tag index"/></br>
                    <a id="removeItemLink" name="removeItemLink_0" href="#"
                       onclick="removeXmlFieldMapping(this)">remove</a>
                    <hr class="style-one"/>
                </div>
            </div>
            <input id="addNewColumnMapping" type="button" class="button" value="Add new...">

            <div id="secondaryTableMappingWrapper" style="display: none;">

            </div>
            <input id="addSecondaryTableMapping" type="button" class="wideButton" value="Add secondary table...">

            <input id="saveFeedButton" type="submit" class="button" value="Save feed">
        </form>
    </div>
    <div id="xmlPreviewContainer" style="width: 600px;">
        <pre id="xmlPreview" class="xmlCode"></pre>
    </div>
</div>
<div id="error"></div>
<div id="secondaryMappingWrapper" style="display: none;">
    <label>Secondary table:</label>
    <select id="secondaryTable" class="secondaryTable" name="secondaryTable_0"
            onchange="secondaryTableChange(this)" required>
    </select></br>
    <hr class="style-one"/>
    <div id="secondaryMappingFieldsWrapper">
        <label>Database column:</label>
        <select id="secondaryTableColumns" class="secondaryTableColumns" name="secondaryTableColumn_0">

        </select></br>
        <label>Xml item:</label>
        <select id="secondaryXmlFields" class="secondaryXmlFields" name="secondaryXmlField_0">

        </select></br>
        <label>Custom action:</label>
        <select id="secondaryActions" class="secondaryActions" name="secondaryAction_0">
            <option value=""></option>
            <?php
            foreach ($listOfActions as $action) {
                echo "<option value=" . $action['Id'] . ">" . $action['Description'] . "</option>";
            }
            ?>
        </select></br>
        <label>Default value:</label>
        <input id="secondaryDefaultValue" class="secondaryDefaultValue" type="text"
               name="secondaryDefaultValue_0"
               placeholder="Input default value"/></br>
        <label>Plain value:</label>
        <input id="secondaryPlainValue" class="secondaryPlainValue" type="text"
               name="secondaryPlainValue_0"
               placeholder="Input plain value if needed"/></br>
        <label>Depends on:</label>
        <select id="secondaryDependsOn" class="secondaryDependsOn" name="secondaryDependsOn_0">

        </select></br>
        <label>XML tag:</label>
        <input id="secondaryXmlTagIndex" class="secondaryXmlTagIndex" type="number"
               name="secondaryXmlTagIndex_0"
               placeholder="Input XML tag index"/></br>
        <a id="secondaryRemoveItemLink" name="secondaryRemoveItemLink_0" href="#"
           onclick="secondaryRemoveXmlFieldMapping(this)">remove secondary</a>
        <hr class="style-one"/>
    </div>
    <input id="addSecondaryColumnMapping" type="button" class="wideButton"
           value="Add secondary column..." onclick="addSecondaryColumnMappingClick(this)">
    <input id="removeSecondaryTableMapping" type="button" class="wideButton"
           value="Remove secondary table..." onclick="secondaryTableMappingRemove(this)">
</div>
</body>
</html>